package com.spark.gaea.mvc.utils;

import com.spark.gaea.utils.DateUtil;
import org.springframework.util.StringUtils;

import java.beans.PropertyEditorSupport;
import java.util.Date;

public class ApolloDateEditor extends PropertyEditorSupport {
	private final boolean allowEmpty;
	private final int exactDateLength;

	public ApolloDateEditor(final boolean allowEmpty) {
		this.allowEmpty = allowEmpty;
		this.exactDateLength = -1;
	}

	public ApolloDateEditor(final boolean allowEmpty, final int exactDateLength) {
		this.allowEmpty = allowEmpty;
		this.exactDateLength = exactDateLength;
	}

	@Override
	public void setAsText(final String text) {
		if (this.allowEmpty && !StringUtils.hasText(text)) {
			this.setValue(null);
		} else {
			if (text != null && this.exactDateLength >= 0 && text.length() != this.exactDateLength) {
				throw new IllegalArgumentException(
						"Could not parse date: it is not exactly" + this.exactDateLength + "characters long");
			}
			try {
				this.setValue(DateUtil.parse(text));
			} catch (RuntimeException ex) {
				throw new IllegalArgumentException("Could not parse date: " + ex.getMessage(), ex);
			}
		}
	}

	@Override
	public String getAsText() {
		final Date value = (Date) this.getValue();
		if (value != null) {
			return DateUtil.format(value);
		}
		return "";
	}
}
